package com.cecsmsserve.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cecsmsserve.entity.HealthRecord;
import com.cecsmsserve.entity.HealthRecordType;
import com.cecsmsserve.entity.HealthStatisticConfig;
import com.cecsmsserve.service.HealthRecordService;
import com.cecsmsserve.service.HealthRecordTypeService;
import com.cecsmsserve.service.HealthStatisticConfigService;
import com.cecsmsserve.utils.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.math.BigDecimal;

@RestController
@RequestMapping("/api/health")
public class HealthRecordController {

    @Autowired
    private HealthRecordService healthRecordService;

    @Autowired
    private HealthRecordTypeService healthRecordTypeService;
    
    @Autowired
    private HealthStatisticConfigService healthStatisticConfigService;

    /**
     * 获取所有启用的健康数据类型
     */
    @GetMapping("/types")
    public CommonResult<List<HealthRecordType>> getTypes() {
        return CommonResult.success(healthRecordTypeService.getActiveTypes());
    }

    /**
     * 添加健康记录
     */
    @PostMapping("/record")
    public CommonResult<Boolean> addRecord(@RequestBody HealthRecord healthRecord) {
        if (healthRecord.getUserId() == null || healthRecord.getTypeId() == null || 
            healthRecord.getRecordValue() == null || healthRecord.getRecordDate() == null) {
            return CommonResult.validateFailed("缺少必要参数");
        }
        
        // 设置当前时间
        if (healthRecord.getRecordTime() == null) {
            healthRecord.setRecordTime(LocalTime.now());
        }
        
        boolean success = healthRecordService.addRecord(healthRecord);
        return success ? CommonResult.success(true) : CommonResult.failed("添加记录失败");
    }

    /**
     * 分页获取用户健康记录
     */
    @GetMapping("/records/{userId}")
    public CommonResult<Page<HealthRecord>> getRecords(
            @PathVariable Integer userId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<HealthRecord> page = healthRecordService.getRecordsByUserIdWithPage(pageNum, pageSize, userId);
        return CommonResult.success(page);
    }

    /**
     * 获取健康记录详情
     */
    @GetMapping("/record/{id}")
    public CommonResult<HealthRecord> getRecordDetail(@PathVariable Integer id) {
        HealthRecord record = healthRecordService.getRecordDetailById(id);
        return record != null ? CommonResult.success(record) : CommonResult.notFound("记录不存在");
    }

    /**
     * 更新健康记录
     */
    @PutMapping("/record")
    public CommonResult<Boolean> updateRecord(@RequestBody HealthRecord healthRecord) {
        if (healthRecord.getId() == null || healthRecord.getUserId() == null) {
            return CommonResult.validateFailed("缺少必要参数");
        }
        
        boolean success = healthRecordService.updateRecord(healthRecord);
        return success ? CommonResult.success(true) : CommonResult.failed("更新记录失败");
    }

    /**
     * 删除健康记录
     */
    @DeleteMapping("/record/{id}")
    public CommonResult<Boolean> deleteRecord(@PathVariable Integer id, @RequestParam Integer userId) {
        boolean success = healthRecordService.deleteRecord(id, userId);
        return success ? CommonResult.success(true) : CommonResult.failed("删除记录失败");
    }

    /**
     * 根据类型和日期范围获取健康记录(用于图表展示)
     */
    @GetMapping("/chart/{userId}/{typeId}")
    public CommonResult<List<HealthRecord>> getChartData(
            @PathVariable Integer userId,
            @PathVariable Integer typeId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        List<HealthRecord> records = healthRecordService.getRecordsByTypeAndDateRange(
                userId, typeId, startDate, endDate);
        return CommonResult.success(records);
    }

    /**
     * 获取用户健康记录统计信息
     */
    @GetMapping("/statistics/{userId}")
    public CommonResult<Map<String, Object>> getStatistics(
            @PathVariable Integer userId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {
        
        // 默认为最近30天
        if (startDate == null) {
            startDate = LocalDate.now().minusDays(30);
        }
        if (endDate == null) {
            endDate = LocalDate.now();
        }
        
        List<Map<String, Object>> statistics = healthRecordService.getTypeStatistics(
                userId, startDate, endDate);
        
        Map<String, Object> result = new HashMap<>();
        result.put("startDate", startDate);
        result.put("endDate", endDate);
        result.put("statistics", statistics);
        
        return CommonResult.success(result);
    }
    
    /**
     * 检查用户某天是否已记录某类型的健康数据
     */
    @GetMapping("/check/{userId}/{typeId}")
    public CommonResult<Integer> checkRecord(
            @PathVariable Integer userId,
            @PathVariable Integer typeId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate recordDate) {
        Integer count = healthRecordService.checkExistingRecord(userId, typeId, recordDate);
        return CommonResult.success(count);
    }

    /**
     * 获取用户健康数据概览（首页使用）
     */
    @GetMapping("/overview/{userId}")
    public CommonResult<List<Map<String, Object>>> getHealthOverview(@PathVariable Integer userId) {
        List<Map<String, Object>> result = new ArrayList<>();
        
        try {
            // 获取用户可见的健康指标配置
            List<HealthStatisticConfig> configs = healthStatisticConfigService.getVisibleConfigsByUserId(userId);
            
            if (configs == null || configs.isEmpty()) {
                // 如果用户没有配置，则获取所有启用的健康数据类型
                List<HealthRecordType> types = healthRecordTypeService.getActiveTypes();
                
                // 只展示前5种类型
                int count = Math.min(types.size(), 5);
                for (int i = 0; i < count; i++) {
                    HealthRecordType type = types.get(i);
                    
                    // 获取该类型的最新记录
                    LambdaQueryWrapper<HealthRecord> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(HealthRecord::getUserId, userId)
                           .eq(HealthRecord::getTypeId, type.getId())
                           .orderByDesc(HealthRecord::getRecordDate)
                           .orderByDesc(HealthRecord::getRecordTime)
                           .last("LIMIT 1");
                    
                    HealthRecord latestRecord = healthRecordService.getOne(wrapper);
                    
                    Map<String, Object> item = createOverviewItem(type, latestRecord);
                    result.add(item);
                }
            } else {
                // 根据用户配置获取健康数据
                for (HealthStatisticConfig config : configs) {
                    HealthRecordType type = healthRecordTypeService.getById(config.getTypeId());
                    
                    if (type != null && type.getStatus()) {
                        // 获取该类型的最新记录
                        LambdaQueryWrapper<HealthRecord> wrapper = new LambdaQueryWrapper<>();
                        wrapper.eq(HealthRecord::getUserId, userId)
                               .eq(HealthRecord::getTypeId, type.getId())
                               .orderByDesc(HealthRecord::getRecordDate)
                               .orderByDesc(HealthRecord::getRecordTime)
                               .last("LIMIT 1");
                        
                        HealthRecord latestRecord = healthRecordService.getOne(wrapper);
                        
                        Map<String, Object> item = createOverviewItem(type, latestRecord);
                        result.add(item);
                    }
                }
            }
            
            return CommonResult.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("获取健康数据概览失败: " + e.getMessage());
        }
    }
    
    // 创建概览项目
    private Map<String, Object> createOverviewItem(HealthRecordType type, HealthRecord record) {
        Map<String, Object> item = new HashMap<>();
        item.put("typeId", type.getId());
        item.put("typeName", type.getName());
        item.put("unit", type.getUnit());
        
        if (record != null) {
            item.put("lastValue", record.getRecordValue());
            
            // 判断是否异常
            boolean isAbnormal = false;
            if (type.getIsNumeric() && type.getMinValue() != null && type.getMaxValue() != null) {
                try {
                    BigDecimal value = new BigDecimal(record.getRecordValue());
                    isAbnormal = value.compareTo(type.getMinValue()) < 0 || 
                                  value.compareTo(type.getMaxValue()) > 0;
                } catch (Exception e) {
                    // 忽略解析错误
                }
            } else {
                isAbnormal = record.getIsAbnormal() != null ? record.getIsAbnormal() : false;
            }
            
            item.put("isAbnormal", isAbnormal);
            
            // 格式化日期
            LocalDate recordDate = record.getRecordDate();
            LocalDate today = LocalDate.now();
            LocalDate yesterday = today.minusDays(1);
            
            String dateStr;
            if (recordDate.equals(today)) {
                dateStr = "今天 ";
            } else if (recordDate.equals(yesterday)) {
                dateStr = "昨天 ";
            } else {
                dateStr = recordDate.format(DateTimeFormatter.ofPattern("MM-dd "));
            }
            
            dateStr += record.getRecordTime().format(DateTimeFormatter.ofPattern("HH:mm"));
            item.put("lastDate", dateStr);
        } else {
            item.put("lastValue", "--");
            item.put("isAbnormal", false);
            item.put("lastDate", "暂无记录");
        }
        
        return item;
    }
} 